package com.beermanager.googleapi.place;

import java.io.IOException;
import java.io.InputStream;
import java.util.LinkedList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.beermanager.utils.IOUtils;

public class GooglePlaceParser {

	public List<PlaceEntry> parse(InputStream inputStream) throws JSONException, IOException {
		
		List<PlaceEntry> places = new LinkedList<PlaceEntry>();
		
		JSONObject json = new JSONObject(IOUtils.readStream(inputStream));		
		JSONArray results = json.getJSONArray("results");
		JSONObject item = null;
		
		for(int i = 0; i < results.length(); i++)
		{
			item = results.getJSONObject(i);			
			places.add(parseOnePlace(item));
		}
		
		return places;
	}

	private PlaceEntry parseOnePlace(JSONObject item) throws JSONException {
		PlaceEntry place = new PlaceEntry();
		
		JSONObject location = item.getJSONObject("geometry").getJSONObject("location");
		
		place.icon = item.has("icon") ? item.getString("icon") : "";		
		place.location = new GooglePlaceLocation(location.has("lat") ? location.getDouble("lat") : 0, 
				location.has("lng") ? location.getDouble("lng") : 0);
		place.id = item.has("id") ? item.getString("id") : null;
		place.name = item.has("name") ? item.getString("name") : null;
		place.reference = item.has("reference") ? item.getString("reference") : null;
		place.vicinity = item.has("vicinity") ? item.getString("vicinity") : null;
		place.rating = item.has("rating") ? item.getDouble("rating") : null;
		return place;
	}
}
